//
//  UIButton+ImagePosition.m
//  ITC_iOS
//
//  Created by iBenz on 2018/9/1.
//  Copyright © 2018年 Benz.L. All rights reserved.
//

#import "UIButton+ImagePosition.h"

@implementation UIButton(ImagePosition)

- (void)buttonImagePosition:(UIButtonImagePosition)position spacing:(CGFloat)spacing {
    [self layoutIfNeeded];
    // 1. 得到imageView和titleLabel的宽、高
    CGFloat imageWidth = 0;
    CGFloat imageHeight = 0;
    if ([UIDevice currentDevice].systemVersion.floatValue >= 8.0) {
        imageWidth = self.imageView.intrinsicContentSize.width;
        imageHeight = self.imageView.intrinsicContentSize.height;
    } else {
        imageWidth = self.imageView.frame.size.width;
        imageHeight = self.imageView.frame.size.height;
    }
    
    CGFloat labelWidth = 0.0;
    CGFloat labelHeight = 0.0;
    if ([UIDevice currentDevice].systemVersion.floatValue >= 8.0) {
        // 由于iOS8中titleLabel的size为0，用下面的这种设置
        labelWidth = self.titleLabel.intrinsicContentSize.width;
        labelHeight = self.titleLabel.intrinsicContentSize.height;
    } else {
        labelWidth = self.titleLabel.frame.size.width;
        labelHeight = self.titleLabel.frame.size.height;
    }
    
    // 2. 声明全局的imageEdgeInsets和labelEdgeInsets
    UIEdgeInsets imageEdgeInsets = UIEdgeInsetsZero;
    UIEdgeInsets labelEdgeInsets = UIEdgeInsetsZero;
    
    // 3. 根据style和space得到imageEdgeInsets和labelEdgeInsets的值
    switch (position) {
        case UIButtonImagePositionTop:
        {
            imageEdgeInsets = UIEdgeInsetsMake(-labelHeight-spacing/2.0, 0, 0, -labelWidth);
            labelEdgeInsets = UIEdgeInsetsMake(0, -imageWidth, -imageHeight-spacing/2.0 -spacing, 0);
        }
            break;
        case UIButtonImagePositionLeft:
        {
            imageEdgeInsets = UIEdgeInsetsMake(0, -spacing/2.0, 0, spacing/2.0);
            labelEdgeInsets = UIEdgeInsetsMake(0, spacing/2.0, 0, -spacing/2.0);
        }
            break;
        case UIButtonImagePositionBottom:
        {
            imageEdgeInsets = UIEdgeInsetsMake(0, 0, -labelHeight-spacing/2.0, -labelWidth);
            labelEdgeInsets = UIEdgeInsetsMake(-imageHeight-spacing/2.0, -imageWidth, 0, 0);
        }
            break;
        case UIButtonImagePositionRight:
        {
            imageEdgeInsets = UIEdgeInsetsMake(0, labelWidth+spacing/2.0, 0, -labelWidth-spacing/2.0);
            labelEdgeInsets = UIEdgeInsetsMake(0, -imageWidth-spacing/2.0, 0, imageWidth+spacing/2.0);
        }
            break;
        default:
            break;
    }
    // 4. 赋值
    self.titleEdgeInsets = labelEdgeInsets;
    self.imageEdgeInsets = imageEdgeInsets;
}

@end
